<template>
  <!--          推荐关注START-->
  <el-card class="aside-cards" shadow="hover">
    <span class="recommend-follow-title">
      <el-icon size="large"><UserFilled /></el-icon>
      推荐关注
    </span>
    <el-skeleton
      :loading="followLoading"
      style="--el-skeleton-circle-size: 40px"
      animated
    >
      <template #template>
        <div
          style="display: flex; gap: 15px; margin: 10px 0; align-items: center"
          v-for="n in pageSize"
        >
          <el-skeleton-item variant="circle" />
          <el-skeleton-item variant="text" style="width: 150px" />
        </div>
      </template>
      <template #default>
        <el-empty
          v-if="currentFollows == null || currentFollows.length === 0"
          description="暂无推荐关注"
        />
        <div class="recommend-follow" v-for="follow in currentFollows" v-else>
          <div>
            <el-avatar
              :src="
                avatarError.get(follow.id)
                  ? `//images.weserv.nl/?url=150.158.52.191:8080/HeadPortrait/default?t=${Math.random().toString(
                      36
                    )}`
                  : `//images.weserv.nl/?url=150.158.52.191:8080/HeadPortrait/${follow.id}?t=${Math.random().toString(
                      36
                    )}`
              "
              @error="avatarError.set(follow.id, !avatarError.get(follow.id))"
              style="cursor: pointer; margin-right: 5px"
              @click="toUser(follow.id)"
            />
            <el-text
              size="large"
              style="cursor: pointer"
              @click="toUser(follow.id)"
              truncated
              >{{ follow.username }}</el-text
            >
          </div>
          <div>
            <el-button
              :icon="Plus"
              :type="follow.followed ? 'info' : 'primary'"
              @click="followUser(follow)"
            >
              {{ follow.followed ? "已关注" : "关注" }}
            </el-button>
          </div>
        </div>
      </template>
    </el-skeleton>
    <el-pagination
      layout="prev, pager, next"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      v-model:page-count="pageCount"
      style="justify-content: center"
      @current-change="pageChange"
    />
  </el-card>
  <!--          推荐关注END-->

  <!--          跳转菜单START-->
  <el-card class="aside-cards" shadow="hover">
    <el-menu class="aside-menu" mode="vertical">
      <router-link class="menu-link" to="personal">
        <el-menu-item index="1">
          <el-icon><Star /></el-icon>我的收藏
        </el-menu-item>
      </router-link>
      <router-link class="menu-link" to="personal">
        <el-menu-item index="2">
          <el-icon><User /></el-icon>我关注的用户
        </el-menu-item>
      </router-link>
      <router-link class="menu-link" to="personal">
        <el-menu-item index="3">
          <el-icon><Reading /></el-icon>我关注的话题
        </el-menu-item>
      </router-link>
      <router-link class="menu-link" to="personal">
        <el-menu-item index="4">
          <el-icon><Connection /></el-icon>我关注的问题
        </el-menu-item>
      </router-link>
    </el-menu>
  </el-card>
  <!--          跳转菜单END-->
</template>

<script setup>
import { ref } from "vue";
import {
  Connection,
  Plus,
  Reading,
  Star,
  User,
  UserFilled,
} from "@element-plus/icons-vue";
import { ElMessage, ElNotification } from "element-plus";
import axios from "axios";
import { useRouter } from "vue-router";

const userId = JSON.parse(localStorage.getItem("user")).id,
  avatarError = ref(new Map()),
  router = useRouter();

const pageSize = ref(4),
  currentPage = ref(1),
  followLoading = ref(true);

// 所有推荐关注和当前页推荐关注
const follows = ref([]),
  currentFollows = ref(undefined),
  pageCount = ref(1);

axios
  .get(`http://localhost:8080/user/recommend?user_id=${userId}`)
  .then((r) => {
    const resp = r.data;
    followLoading.value = false;
    if (resp.status === 0) {
      follows.value = resp.data;
      currentFollows.value = follows.value.slice(0, pageSize.value);
      currentFollows.value.forEach(follow => {
        avatarError.value.set(follow.id, false)
      })
      pageCount.value =
        Math.floor(follows.value.length / pageSize.value) +
        (follows.value.length % pageSize.value === 0 ? 0 : 1);
    } else {
      ElMessage.error("推荐关注加载失败，请检查网络连接是否正常");
    }
  })
  .catch((error) => {
    followLoading.value = false;
    console.log(error.request.response);
    ElNotification.error("推荐关注加载失败，请检查网络连接是否正常");
  });

function pageChange() {
  const PAGE = currentPage.value,
    SIZE = pageSize.value;
  currentFollows.value = follows.value.slice((PAGE - 1) * SIZE, PAGE * SIZE);
  currentFollows.value.forEach(follow => {
    avatarError.value.set(follow.id, false)
  })
}

const followUser = (follow) => {
  if (follow.followed) {
    axios
      .delete(
        `http://localhost:8080/follow?type=0&from_id=${userId}&to_id=${follow.id}`
      )
      .then((r) => {
        const resp = r.data;
        if (resp.status === 0) {
          follow.followed = false;
        } else {
          ElNotification.error("取消关注失败，请检查网络连接是否正常");
        }
      })
      .catch((error) => {
        console.log(error.request.response);
        ElNotification.error("取消关注失败，请检查网络连接是否正常");
      });
  } else {
    axios
      .post(
        `http://localhost:8080/follow?type=0&from_id=${userId}&to_id=${follow.id}`
      )
      .then((r) => {
        const resp = r.data;
        if (resp.status === 0) {
          follow.followed = true;
        } else {
          ElNotification.error("关注失败，请检查网络连接是否正常");
        }
      })
      .catch((error) => {
        console.log(error.request.response);
        ElNotification.error("关注失败，请检查网络连接是否正常");
      });
  }
};

const toUser = (id) => {
  let page = router.resolve({
    path: "/other",
    query: {
      user_id: id,
    },
  });
  window.open(page.href, "_blank");
};

defineExpose({
  followUser,
  toUser,
});
</script>

<style scoped>
.aside-cards {
  margin: 20px 10px;
}
.aside-menu {
  border-right: 0;
}
.menu-link {
  text-decoration: none;
}
.recommend-follow-title {
  display: flex;
  gap: 5px;
  font-size: 15px;
}
.recommend-follow {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
}
.recommend-follow div {
  display: flex;
  gap: 5px;
  text-align: center;
}
</style>
